package org.lgiavedoni.android.franq.service.phone.listener;

import java.util.ArrayList;
import java.util.List;

import org.lgiavedoni.android.franq.core.listener.PhoneListener;
import org.lgiavedoni.android.franq.core.service.Service;
import org.lgiavedoni.android.franq.service.log.Logger;
import org.lgiavedoni.android.franq.service.phone.ContextService;

public class PhoneListenerService extends Service {

	public static final PhoneListenerService inst = new PhoneListenerService();
	private final List<PhoneListener> listeners = new ArrayList<PhoneListener>();
	private static final String IMPLEMENTATIONS_KEY = "phoneListeners";

	public PhoneListenerService() {
	}

	@Override
	public String getServiceName() {
		return "phoneListeners";
	}

	@Override
	protected void startInternal() {
		if (ContextService.inst.isApplicationContextLoaded())
			for (Object obj : getImplementations(IMPLEMENTATIONS_KEY)) {
				listeners.add((PhoneListener) obj);
			}
	}

	@Override
	protected void stopInternal() {
		for (PhoneListener listener : listeners) {
			listener.unregisterListener();
		}
	}

	@Override
	public void _run() {
		if (ContextService.inst.getApplicationContext() != null) {
			for (PhoneListener listener : listeners) {
				listener.registerListener();
			}
		} else {
			Logger.inst.warning("The service[" + getServiceName() + " cant start! The application context is not initialized");
			setStatus(Status.STOPPED);
		}
	}
}
